<template>
  <div class="search-container">
    <div class="search-box flex-box">
      <button class="back-icon" @click="routeBack">
        <svg class="icon" aria-hidden="true">
          <use xlink:href="#icon-gb-xiazai6"></use>
        </svg>
      </button>
      <i></i>
      <input type="text" :placeholder="initSearchWords[initSearchIndex]" @keypress="searchKeyCommit" v-model="searchWords" @input='searchChange' ref="searcher" id="searcher">
      <button class="search-icon" @click="searchCommit(null)">搜索</button>
    </div>
    <div class="search-main" v-show="showIndex">
      <div class="search-top">
        <h3>热门搜索</h3>
        <img src="../assets/img/xqs-750.jpg" alt="">
      </div>
      <div class="search-lists">
        <ul>
          <li v-for="(item,index) in hotSearch" :key="index" @click="searchCommit(item)"><p>{{item}}</p></li>
        </ul>
      </div>
      <div class="search-history" v-show="searchHistory.length">
        <h3>搜索记录</h3>
        <ul>
          <li class="flex-box" v-for="(item,index) in searchHistory" :key="index">
            <p @click="searchCommit(item)"><i></i>{{item}}</p>
            <button class="remove-item" @click="removeItem(item)">
              <svg class="icon" aria-hidden="true">
                <use xlink:href="#icon-gb-untitled94"></use>
              </svg>
            </button>
          </li>
          <li class="clear"><button @click="clearHistory">清除搜索记录</button></li>
        </ul>
      </div>
    </div>
    <div class="search-res" v-show="!showIndex">
      <div class="search-tips">
        <div class="tips-header">
          <h2>{{searchWords}}</h2><p>商品筛选（共<span>{{total}}</span>个商品）</p>
          <button @click="showTipLists" v-if="proTags || selectTags">筛选</button>
        </div>
      </div>
      <div class="search-res-box" @scroll="scrollPage" ref="scrollBox">
        <ul class="search-res-lists" v-if="resLists.length">
          <li v-for="(item,index) in resLists" :key="index" @click="toProDetail(item.id)">
            <div class="img-box">
              <img v-if="item.img" :src="$BASEPATH + item.img.path">
            </div>
            <div class="des-box">
              <p>{{item.name}}</p>
              <h5>{{item.prodDesc}}</h5>
              <h6><i>￥</i>{{item.price}}<span v-if="item.marketPrice">￥{{item.marketPrice}}</span></h6>
            </div>
          </li>
        </ul>
        <div class="search-none" v-else>
          <img src="../assets/img/search-icon02.png" alt="">
          <p>没有相关商品</p>
        </div>
        <div class="loading-data flex-box" :class="{active:dataMore}">
          <p v-if="isEnd">- 没有更多了 -</p>
          <p v-else>加载更多数据<img src="../assets/img/more-loading.gif"></p>
        </div>
      </div>
    </div>
    <div class="loading-box" v-show="showLoading">
      <loading/>
    </div>
    <transition mode="out-in"
      name="fade-in"
      enter-active-class='slide-active'
      leave-active-class='slide-active'>
      <div class="tips-main" v-show="showTipsMain" @click.self="closeTips">
        <transition mode="out-in"
        name="slide-in"
        enter-active-class='slide-active'
        leave-active-class='slide-active'>
        <div class="tips-main-box" v-show="showTipsMain">
          <ul v-if="selectTags">
            <li class="selected-title"><div>已选标签</div></li>
            <li class="flex-box" v-for="(item,index) in selectTags" :key="index">
              <div class="left-box">{{item.name}}</div>
              <div class="right-box">
                <div class="selected-item" v-for="(items,indexs) in item.options" :key="indexs" @click="removeTag(items.id)">
                  {{items.optionValue}}&nbsp;
                  <svg class="icon" aria-hidden="true">
                    <use xlink:href="#icon-gb-untitled94"></use>
                  </svg>
                </div>
              </div>
            </li>
          </ul>
          <ul v-if="proTags">
            <li class="flex-box" v-for="(item,index) in proTags" :key="index">
              <div class="left-box">{{item.name}}</div>
              <div class="right-box"><p @click="CheckTip(items.id)" :class="{active:selectedItems.includes(items.id)}" v-for="(items,indexs) in item.options" :key="indexs">{{items.optionValue}}</p></div>
            </li>
          </ul>
          <div class="tip-main-footer">
            <button class="reset-tips" @click="resetTips">重置</button>
            <button class="commit-tips" @click="commitTips">确认</button>
          </div>
        </div>
        </transition>
      </div>
    </transition>
  </div>
</template>

<script>
// @ is an alias to /src
export default {
  name: 'mallIndex',
  data() {
    return {
      lists: null,
      searchWords: '',
      showLoading: false,
      showIndex: true,
      total: '',
      dataMore: false,
      isEnd: false,
      initPageSize: 20,
      currentPage: 1,
      showTipsMain: false,
      loadingDes: '加载更多数据',
      hotSearch: ['印加果温润面膜', '印加果眼霜', '益健益生菌', '虾青素面膜', '微醺', '解腻'],
      searchHistory: [],
      initSearchWords: ['益生菌', '印加果', '面膜', 'iphone12', '华为手机', '护肤'],
      initSearchIndex: 0,
      resLists: [],
      proTags: '',
      selectTags: '',
      selectedItems: []
    }
  },
  components: {},
  computed: {},
  methods: {
    removeItem(item) {
      // console.log(item)
      this.searchHistory.splice(this.searchHistory.indexOf(item), 1)
      localStorage.setItem('searchHistory', JSON.stringify(this.searchHistory))
    },
    toProDetail(goodsId) {
      this.$router.push({ name: 'productdetail', params: { id: goodsId } })
    },
    clearHistory() {
      this.searchHistory = []
      localStorage.setItem('searchHistory', '[]')
    },
    routeBack() {
      this.$router.go(-1)
    },
    // 搜索确认
    searchCommit(item, tagIds) {
      if (item) {
        this.searchWords = item
      } else {
        if (!this.searchWords.trim()) {
          this.searchWords = this.$refs.searcher.placeholder
        }
      }
      let params
      this.currentPage = 1
      if (tagIds) {
        params = {
          keywords: this.searchWords,
          pageSize: this.initPageSize,
          currentPage: this.currentPage,
          tagIds: tagIds.join()
        }
      } else {
        params = {
          keywords: this.searchWords,
          pageSize: this.initPageSize,
          currentPage: this.currentPage
        }
      }
      this.showLoading = true
      this.$API
        .searcher(params)
        .then(data => {
          console.log(data)
          this.showLoading = false
          this.showIndex = false
          if (data.flag) {
            // 处理搜索记录
            this.resLists = data.data
            this.total = data.totalCount
            this.proTags = data.tags.tags
            this.selectTags = data.tags.selectedTags
            if (!this.searchHistory.includes(this.searchWords)) {
              this.searchHistory.unshift(this.searchWords)
              if (this.searchHistory.length > 10) {
                this.searchHistory.pop()
              }
            } else {
              let i = this.searchHistory.indexOf(this.searchWords)
              this.searchHistory.unshift(this.searchHistory.splice(i, 1)[0])
            }
            localStorage.setItem('searchHistory', JSON.stringify(this.searchHistory))
          } else {
            this.$layer.msg(data.msg)
          }
        })
        .catch(err => {
          this.showLoading = false
          alert(err)
        })
    },
    // 列表区滚动事件
    scrollPage(e) {
      // console.log(e.target.scrollTop)
      // console.log(this.$refs.selectNav.offsetTop)
      let m = Math.floor(e.target.scrollTop), //滚动高度
        // n = this.$refs.selectNav.offsetTop, //元素距离顶部高度
        o = this.$refs.scrollBox.clientHeight,
        p = e.target.scrollHeight
      //判断页面滚动到底部
      // alert(o + '' + p)
      if (p > o && m + o === p) {
        this.scrollToBottom = true
      } else {
        this.scrollToBottom = false
      }
      if (this.scrollToBottom) {
        this.dataMore = true
        if (this.resLists.length < this.total) {
          this.isEnd = false
          this.currentPage++
          let params = {
            keywords: this.searchWords,
            pageSize: this.initPageSize,
            currentPage: this.currentPage
          }
          this.$API
            .searcher(params)
            .then(data => {
              if (data.flag) {
                this.resLists.push(...data.data)
              } else {
                this.$layer.msg(data.msg)
              }
              this.dataMore = false
            })
            .catch(err => {
              alert(err)
            })
        } else {
          this.isEnd = true
          setTimeout(() => {
            this.dataMore = false
          }, 2500)
        }
      }
      // this.navFixed = m - n > 0 ? true : false //导航栏到顶就固定
    },
    searchChange() {
      //监测输入框变化
      if (!this.searchWords) {
        this.showIndex = true
      }
      // console.log('ppp')
    },
    searchKeyCommit(e) {
      if (e.keyCode == 13) {
        e.preventDefault()
        //请求搜索接口
        alert('test')
      }
    },
    // 选择标签
    CheckTip(id) {
      if (this.selectedItems.includes(id)) {
        let i = this.selectedItems.indexOf(id)
        this.selectedItems.splice(i, 1)
      } else {
        this.selectedItems.push(id)
      }
    },
    // 重置标签
    resetTips() {
      this.selectedItems = []
      this.showTipsMain = false
      this.searchCommit(this.searchWords, this.selectedItems)
    },
    // 确认标签
    commitTips() {
      if (this.selectedItems.length) {
        // this.selectedItems.forEach(item=>{
        // })
        console.log(this.selectedItems)
        this.searchCommit(this.searchWords, this.selectedItems)
      }
      this.showTipsMain = false
    },
    // 删除已选标签
    removeTag(id) {
      this.showTipsMain = false
      this.selectedItems.splice(this.selectedItems.indexOf(id), 1)
      this.searchCommit(this.searchWords, this.selectedItems)
      console.log(this.currentPage)
    },
    showTipLists() {
      this.showTipsMain = true
    },
    closeTips() {
      this.showTipsMain = false
    }
  },
  created() {
    // 初始化搜索历史
    this.searchHistory = JSON.parse(localStorage.getItem('searchHistory'))
      ? JSON.parse(localStorage.getItem('searchHistory'))
      : []
    // console.log(aa)
  },
  mounted() {
    this.$refs.searcher.focus()
    let l = this.initSearchWords.length
    setInterval(() => {
      // 修改搜索框placeholder
      this.initSearchIndex++
      if (this.initSearchIndex >= l) {
        this.initSearchIndex = 0
      }
    }, 3000)
  }
}
</script>
<style scoped lang="scss">
.search-container {
  width: 100%;
  height: 100vh;
  background: #fff;
  box-shadow: 0 4px 8px rgba($color: #000000, $alpha: 0.2);
  .search-box {
    width: 100%;
    height: 42px;
    background: #f0f0f0;
    position: relative;
    box-sizing: border-box;
    padding: 8px 15px;
    position: relative;
    .back-icon {
      border: none;
      width: 24px;
      padding-left: 0;
      padding-right: 8px;
      font-size: 14px;
      color: #666;
      background: none;
    }
    .search-icon {
      border: none;
      outline: none;
      font-size: 14px;
      background: none;
      color: #333;
      padding: 0;
      padding-left: 8px;
      letter-spacing: 2px;
      white-space: nowrap;
    }
    input {
      width: 100%;
      height: 100%;
      border-radius: 4px;
      line-height: 26px;
      background: #fff;
      box-sizing: border-box;
      font-size: 14px;
      padding-left: 36px;
      padding-right: 10px;
      -webkit-appearance: none;
      border: 1px solid #fff;
      color: #666;
    }
    input::-webkit-input-placeholder {
      color: #aaa;
      line-height: 26px;
    }
    i {
      width: 16px;
      height: 16px;
      font-family: 'iconfont-gb' !important;
      fill: currentColor;
      font-size: 14px;
      font-style: normal;
      -webkit-font-smoothing: antialiased;
      -moz-osx-font-smoothing: grayscale;
      position: absolute;
      z-index: 66;
      left: 48px;
      top: 15px;
      &::before {
        color: #aaa;
        content: '\e622';
      }
    }
    &::after {
      position: absolute;
      width: 100%;
      content: '';
      bottom: 0;
      left: 0;
      border-bottom: 1px solid #d8d8d8;
      transform: scaleY(0.5);
      transform-origin: bottom; // 设置缩放基点
    }
  }
  .search-main,
  .search-res {
    width: 100%;
    height: calc(100% - 42px);
    overflow-y: auto;
    .search-none {
      width: 100%;
      text-align: center;
      padding: 36px 0;
      img {
        width: 200px;
      }
      p {
        font-size: 14px;
        color: #333;
      }
    }
    .search-tips {
      width: 100%;
      background: #f0f0f0;
      text-align: left;
      padding: 16px 15px 6px 15px;
      box-sizing: border-box;
      .tips-header {
        margin-bottom: 10px;
        button {
          float: right;
          font-size: 14px;
          height: 22px;
          line-height: 22px;
          width: 56px;
          display: block;
          background: none;
          padding: 0;
          outline: none;
          border: 1px solid #666;
          position: relative;
          top: -2px;
        }
      }
      h2 {
        font-size: 18px;
        color: #333;
        color: #1c93d0;
        text-align: left;
        display: inline;
      }
      p {
        font-size: 14px;
        display: inline;
        margin-left: 6px;
        color: #999;
      }
    }
    .search-res-box {
      width: 100%;
      position: fixed;
      top: 92px;
      bottom: 0;
      left: 0;
      background: #fff;
      z-index: 8;
      overflow-y: auto;
      overflow-x: hidden;
      -webkit-overflow-scrolling: touch;
      .loading-data {
        width: 100%;
        opacity: 0;
        color: #666;
        height: 28px;
        background: #fff;
        box-sizing: border-box;
        overflow: hidden;
        border: 1px solid #eee;
        transition: opacity 0.05s ease-in-out;
        -webkit-transition: opacity 0.05s ease-in-out;
        .state-a {
          display: none;
        }
        .state-b {
          display: inline;
        }
        img {
          width: 20px;
        }
        &.active {
          opacity: 1;
          .state-a {
            display: inline;
          }
          .state-b {
            display: none;
          }
        }
      }
    }
    .search-res-lists {
      width: 100%;
      overflow: hidden;
      padding: 10px 12px;
      box-sizing: border-box;
      li {
        width: 100%;
        float: left;
        padding: 10px 0;
        box-sizing: border-box;
        border-bottom: 1px solid #eee;
        &:last-child {
          border: none;
        }
        .img-box {
          width: 80px;
          height: 80px;
          float: left;
          background: #eee;
          img {
            width: 100%;
            height: 100%;
          }
        }
        .des-box {
          height: 80px;
          width: calc(100% - 80px);
          float: left;
          text-align: left;
          position: relative;
          padding: 2px 0;
          padding-left: 10px;
          box-sizing: border-box;
          // margin-left: 100px;
          p {
            font-size: 14px;
            color: #333;
            line-height: 20px;
            margin-bottom: 2px;
          }
          h5 {
            font-size: 12px;
            color: #999;
            line-height: 14px;
          }
          h6 {
            position: absolute;
            bottom: 2px;
            left: 10px;
            color: #ff6363;
            width: 100%;
            font-size: 16px;
            vertical-align: bottom;
            i {
              font-size: 12px;
            }
            span {
              float: right;
              margin-right: 16px;
              font-size: 12px;
              color: #aaa;
              position: relative;
              top: 4px;
              text-decoration: line-through;
            }
          }
        }
      }
    }
  }
  .search-top {
    width: 100%;
    text-align: left;
    float: left;
    padding: 0 15px;
    box-sizing: border-box;
    h3 {
      font-size: 14px;
      font-weight: bold;
      color: #666;
      padding: 15px 0;
    }
    img {
      width: 100%;
      border-radius: 4px;
      overflow: hidden;
    }
  }
  .search-lists {
    width: 100%;
    padding: 10px;
    box-sizing: border-box;
    float: left;
    ul li {
      float: left;
      padding: 5px 5px;
      box-sizing: border-box;
      p {
        display: block;
        padding: 6px 15px;
        border: 1px solid #ccc;
      }
      &:first-child {
        p {
          background: rgb(238, 250, 255);
          border: 1px solid rgb(169, 231, 255);
        }
      }
      &:nth-child(2) {
        p {
          background: rgb(238, 255, 251);
          border: 1px solid rgb(105, 250, 255);
        }
      }
      &:nth-child(3) {
        p {
          background: rgb(255, 238, 254);
          border: 1px solid rgb(255, 169, 241);
        }
      }
      &:nth-child(4) {
        p {
          background: rgb(238, 255, 242);
          border: 1px solid rgb(169, 255, 202);
        }
      }
      &:nth-child(5) {
        p {
          background: rgb(255, 255, 238);
          border: 1px solid rgb(255, 228, 169);
        }
      }
      &:nth-child(6) {
        p {
          background: rgb(247, 238, 255);
          border: 1px solid rgb(216, 169, 255);
        }
      }
    }
  }
  .search-history {
    width: 100%;
    text-align: left;
    float: left;
    padding-top: 10px;
    border-top: 6px solid #eee;
    h3 {
      font-size: 14px;
      font-weight: bold;
      color: #666;
      padding: 5px 15px;
    }
    ul {
      width: 100%;
      padding: 10px 15px;
      float: left;
      display: block;
      box-sizing: border-box;
      li {
        width: 100%;
        padding: 5px 0;
        float: left;
        line-height: 28px;
        position: relative;
        box-sizing: border-box;
        justify-content: space-between;
        -webkit-justify-content: space-between;
        button.remove-item {
          width: 28px;
          height: 28px;
          background: none;
          border: none;
          outline: none;
          font-size: 12px;
          color: #ccc;
        }
        p {
          font-size: 14px;
        }
        &::after {
          width: 100%;
          position: absolute;
          bottom: 0;
          left: 0;
          border-bottom: 1px solid #ccc;
          content: '';
          transform: scaleY(0.3333);
          transform-origin: bottom; // 设置缩放基点
        }
        i {
          width: 16px;
          height: 16px;
          font-family: 'iconfont-gb' !important;
          fill: currentColor;
          font-size: 16px;
          margin-right: 8px;
          font-style: normal;
          display: block;
          float: left;
          -webkit-font-smoothing: antialiased;
          -moz-osx-font-smoothing: grayscale;
          &::before {
            color: #aaa;
            content: '\e600';
          }
        }
        &.clear {
          text-align: center;
          line-height: 36px;
          font-size: 18px;
          color: #666;
          button {
            font-size: 14px;
            border: none;
            background: none;
            outline: none;
          }
        }
      }
    }
  }
  .tips-main {
    padding-top: 12px;
    overflow: hidden;
    background: rgba($color: #000000, $alpha: 0.6);
    padding: 10px;
    box-sizing: border-box;
    position: fixed;
    right: 0;
    top: 0;
    width: 100%;
    height: 100%;
    z-index: 99;
    .tips-main-box {
      width: 280px;
      height: 100%;
      background: #fff;
      position: absolute;
      right: 0;
      top: 0;
      .selected-title {
        border: none;
        width: 100%;
        padding: 0;
        background: #1c93d0;
        height: 24px;
        color: #fff;
        margin-bottom: 8px;
        line-height: 24px;
      }
    }
    .tip-main-footer {
      position: absolute;
      bottom: 0;
      left: 0;
      width: 100%;
      height: 42px;
      background: #eee;
      button {
        width: 50%;
        float: left;
        height: 100%;
        border: none;
        outline: none;
        font-size: 14px;
        &.commit-tips {
          background: #1c93d0;
          color: #fff;
        }
      }
    }
    ul {
      margin: 15px 0;
      padding: 0 15px;
      box-sizing: border-box;
      border-bottom: 8px solid #f0f0f0;
      li {
        margin-bottom: 6px;
        width: 100%;
        padding: 5px 0;
        box-sizing: border-box;
        overflow: hidden;
        justify-content: flex-start;
        -webkit-justify-content: flex-start;
        align-items: flex-start;
        -webkit-align-items: flex-start;
        // white-space: nowrap;
        flex-wrap: wrap;
        -webkit-flex-wrap: wrap;
        border-bottom: 4px solid #eee;
        .left-box {
          font-size: 12px;
          line-height: 18px;
          width: 100%;
          color: #555;
          font-weight: bold;
          white-space: nowrap;
          text-align: left;
          margin-bottom: 6px;
        }
        .right-box {
          text-align: left;
          p,
          .selected-item {
            line-height: 16px;
            font-size: 12px;
            color: #999;
            display: inline-block;
            border: 1px solid rgb(213, 213, 213);
            padding: 2px 6px;
            border-radius: 12px;
            margin-bottom: 6px;
            margin-right: 6px;
            &.active {
              border: 1px solid rgb(72, 137, 211);
              background: #6ab5f5;
              color: #fff;
            }
          }
          .selected-item {
            border-color: rgb(255, 182, 182);
            svg {
              font-size: 10px;
              color: #f00;
            }
          }
        }
        &:last-child {
          border-bottom: none;
        }
      }
    }
  }
}
.loading-box {
  position: fixed;
  top: 48px;
  left: 0;
  width: 100%;
  bottom: 0;
  z-index: 99;
  background: rgba($color: #ffffff, $alpha: 0.9);
}
.slide-active {
  transition: 0.3s cubic-bezier(0.55, 0, 0.1, 1);
  transition-property: opacity, transform;
}
.slide-in-enter,
.slide-in-leave-to {
  opacity: 0;
  transform: translate3d(30%, 0, 0);
}
.fade-in-enter,
.fade-in-leave-to {
  opacity: 0;
}
</style>
